﻿using System.Linq;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Controls;
using nyxwin.Common.Base.Utils;
using nyxwin.Common.Settings;
using nyxwin.Data.Mail;

namespace nyxwin.Scheduled
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;

        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                System.Diagnostics.Debugger.Break();
            }
        }

        protected override void OnInvoke(ScheduledTask task)
        {
            if (task is PeriodicTask && task.Name == Constants.MailCheckPeriodicTaskName)
            {
                //var mailManager = new MailManager(ApplicationSettings.Instance.AuthorizationNick, ApplicationSettings.Instance.AuthorizationToken);
                //mailManager.GetMailsCompleted +=
                //    (sender, args) =>
                //    {
                //        try
                //        {
                //            var unread = args.MailList.Where(m => m.Unread).Count();
                //            var lastFrom = args.MailList.Where(m => m.Unread).FirstOrDefault();

                //            var tile = ShellTile.ActiveTiles.FirstOrDefault();
                //            if (tile != null)
                //            {
                //                tile.Update(new StandardTileData() { Count = unread });
                //            }

                //            if (lastFrom != null)
                //            {
                //                var toast = new ShellToast();
                //                toast.Title = lastFrom.Nick;
                //                toast.Content = lastFrom.Content.Length > 24 ? lastFrom.Content.Substring(0, 24) : lastFrom.Content;
                //                toast.Show();
                //            }
                //        }
                //        catch
                //        {
                //            /* TODO: ISOTOXIN: Log exception */
                //        }
                //        finally
                //        {
                //            NotifyComplete();
                //        }
                //    };

                //mailManager.GetMails(MailQuery.Default);
            }
        }
    }
}